import { setStore, getStore } from '@/util/store'
import { isURL, validatenull } from '@/util/validate'
import { deepClone } from '@/util/util'
import webiste from '@/config/website'
import { login, getInfo, logout } from '@/api/login'
import { getMenus } from '@/api/menu'
import { getAccessToken, getRefreshToken, setAccessToken, setRefreshToken } from '@/data/user'

const user = {
  state: {
    userInfo: {},
    permission: {},
    nettyStatus: false,
    roles: [],
    menuId: getStore({ name: 'menuId' }) || [],
    menu: getStore({ name: 'menu' }) || [],
    menuAll: getStore({ name: 'menuAll' }) || [],
    token: getStore({ name: 'token' }) || '',
    permissions: [],
    access_token: getAccessToken(),
    refresh_token: getRefreshToken(),
    serverPort: '',
    staticPort: '',
    pageScale: getStore({ name: 'pageScale' }) || 100

  },
  actions: {
    // 根据用户名登录
    LoginByUsername({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          commit('SET_ACCESS_TOKEN', res.access_token)
          commit('SET_REFRESH_TOKEN', res.refresh_token)
          commit('DEL_ALL_TAG')
          commit('CLEAR_LOCK')
          resolve(res.verification)
        })
          .catch(err => {
            console.error(err)
            reject()
          })
      })
    },

    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then((res) => {
          const user = res.data || {}
          document.body.style.zoom = getStore({ name: 'pageScale' }) + "%";
          user.avatar = !user.avatar ? require('@/assets/img/avatar.png') : process.env.VUE_APP_BASE_API + user.avatar
          if (user.roleList && user.roleList.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', user.roleList)
            commit('SET_PERMISSIONS', user.permissions)
          } else {
            // commit('SET_ROLES', ['ROLE_DEFAULT'])
            return
          }
          commit('SET_USERIFNO', user)
          resolve(user)
        }).catch(err => {
          reject(err)
        }
        )
      })
    },
    // // 刷新token
    // RefeshToken({ state, commit }) {
    //   return new Promise((resolve, reject) => {
    //     refeshToken(state.refeshToken).then(res => {
    //       const data = res.data.data
    //       commit('SET_ACCESS_TOKEN', data)
    //       resolve(data)
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_ACCESS_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '')
          commit('SET_MENUID', {})
          commit('SET_MENUALL', [])
          // commit('SET_PAGESCALE', 100)
          commit('SET_MENU', [])
          commit('SET_TAG_LIST', [])
          commit('SET_ROLES', [])
          commit('SET_USERIFNO', {})
          commit('DEL_ALL_TAG')
          commit('CLEAR_LOCK')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 注销session
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_ACCESS_TOKEN', '')
        commit('SET_REFRESH_TOKEN', '')
        commit('SET_MENUID', {})
        commit('SET_MENUALL', [])
        // commit('SET_PAGESCALE', 100)
        commit('SET_MENU', [])
        commit('SET_TAG_LIST', [])
        commit('SET_ROLES', [])
        commit('SET_USERIFNO', {})
        commit('DEL_ALL_TAG')
        commit('CLEAR_LOCK')
        resolve()
      })
    },
    // 是否连接websocket
    NettyStatus({ commit }, status) {
      return new Promise(resolve => {
        commit('SET_NETTYSTATUS', status)
        resolve()
      })
    },
    // GetTopMenu() {
    //   return new Promise(resolve => {
    //     getTopMenu().then((res) => {
    //       const data = res.data.data || []
    //       resolve(data)
    //     })
    //   })
    // },
    // 获取系统菜单
    GetMenu({ commit }, parentId) {
      return new Promise(resolve => {
        getMenus(parentId).then((res) => {
          const data = [...res.data]
          console.log(`<<<<2023年04月23日 10:50:14>>>>`, { 'menu': data })

          const menu = deepClone(data)
          menu[0].children.push({
            alwaysShow: false,
            children: null,
            component: "ips/device/callboxManage",
            hidden: false,
            icon: "device1",
            label: "叫号器管理",
            meta: {
              icon: "device1",
              noCache: true,
              title: "叫号器管理"
            },
            name: "CallboxManage",
            path: "callboxManage",
            redirect: null
          })
          menu.forEach(ele => {
            addPath(ele, true)
          })
          menu.unshift({
            label: '首页',
            path: '/wel/index',
            icon: 'documentation',
            meta: {
              title: '首页'
            },
            components: require(['@/views/wel/index'], resolve)
          })
          console.log('menu', menu)
          commit('SET_MENUALL', menu)
          commit('SET_MENU', menu)
          resolve(menu)
        })
      })
    }
  },
  mutations: {
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_NETTYSTATUS: (state, nettyStatus) => {
      state.nettyStatus = nettyStatus
      setStore({ name: 'nettyStatus', content: nettyStatus })
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ACCESS_TOKEN: (state, access_token) => {
      setAccessToken(access_token)
      state.access_token = access_token
    },
    SET_REFRESH_TOKEN: (state, refresh_token) => {
      setRefreshToken(refresh_token)
      state.refresh_token = refresh_token
    },
    SET_MENUID(state, menuId) {
      state.menuId = menuId
      setStore({ name: 'menuId', content: state.menuId, type: 'session' })
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_MENUALL: (state, menuAll) => {
      state.menuAll = menuAll
      setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_PAGESCALE: (state, pageScale) => {
      state.pageScale = pageScale
      setStore({ name: 'pageScale', content: state.pageScale })
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      setStore({ name: 'menu', content: state.menu })
      if (validatenull(menu)) return
      // 合并动态路由去重
      let menuAll = state.menuAll
      menuAll = menuAll.concat(menu).reverse()
      const newMenu = []
      for (const item1 of menuAll) {
        let flag = true
        for (const item2 of newMenu) {
          if (item1.label === item2.label || item1.path === item2.path) {
            flag = false
          }
        }
        if (flag) newMenu.push(item1)
      }
      state.menuAll = newMenu
      setStore({ name: 'menuAll', content: state.menuAll, type: 'session' })
    }
  }

}
export default user

function addPath(ele, first) {
  const menu = webiste.menu
  const propsConfig = menu.props
  const propsDefault = {
    label: propsConfig.label || 'label',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children'
  }
  const icon = ele[propsDefault.icon]

  ele['component'] = ele.component ? (ele.component !== '#' ? 'views/' + ele.component : '#') : ''
  ele[propsDefault.label] = ele.meta ? ele.meta.title : ''
  ele[propsDefault.icon] = ele.meta ? ele.meta.icon : icon

  // ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
  const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0
  if (isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path].replace(/&/g, '$')
  }
  if (!isChild && first && !isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path] + '/index'
  } else {
    ele[propsDefault.children] && ele[propsDefault.children].forEach(child => {
      if (!isURL(child[propsDefault.path])) {
        child[propsDefault.path] = `${ele[propsDefault.path]}/${child[propsDefault.path] ? child[propsDefault.path] : 'index'}`
      }
      addPath(child)
    })
  }
}
